import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { AppService } from './app.service';
import * as fs from 'fs';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Post('file')
  @UseInterceptors(FileInterceptor('files', { dest: 'upload' }))
  uploadFiles(@UploadedFile() files: Express.Multer.File, @Body() body: any) {
    // 获取文件名，用来做文件夹名
    const fileName = body.name.match(/(.+)\-\d+$/)[1];

    const chunkDir = 'upload/chunks_' + fileName;

    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir);
    }

    fs.cpSync(files.path, chunkDir + '/' + body.name);

    fs.rmSync(files.path);
  }

  // 将文件分片合并
  @Get('merge')
  merge(@Query('fileName') fileName: string) {
    console.log(fileName);

    const chunkDir = 'upload/chunks_' + fileName;

    const files = fs.readdirSync(chunkDir);

    let startPos = 0;
    let count = 0;

    files.map((file) => {
      const filePath = chunkDir + '/' + file;
      const stream = fs.createReadStream(filePath);
      stream
        .pipe(fs.createWriteStream('upload/' + fileName, { start: startPos }))
        .on('finish', () => {
          count++;
          console.log(count);
          if (count === files.length) {
            fs.rmdirSync(chunkDir, { recursive: true });
          }
        });

      startPos += fs.statSync(filePath).size;
    });
  }
}
